package models

import (
	"github.com/astaxie/beego"
	"github.com/go-redis/redis"
	"strconv"
	"time"
)

func rconnect() *redis.Client {
	redis_host := beego.AppConfig.String("redis_host")
	client := redis.NewClient(&redis.Options{
		Addr:     redis_host,
		Password: "",
		DB:       0,
	})
	_, err := client.Ping().Result()

	if err != nil {
		log := UitlLog()
		log.Error("redis link err" + err.Error())
	}
	return client
}

func SetRedis(msg_id string, i int, onedata []byte) error {
	client := rconnect()
	defer client.Close()
	//fmt.Println(client)
	//ranking := []redis.Z{
	//	redis.Z{1, valbyte},
	//}
	//client.ZAdd("kak", ranking[0])
	key := "msg" + msg_id

	score, _ := strconv.ParseFloat(string(i), 64)
	//if errf != nil {
	//	log := UitlLog()
	//	log.Error("string数据转换float64 err" + errf.Error())
	//	return errf
	//}
	err := client.ZAdd(key, redis.Z{Score: score, Member: onedata}).Err()
	//设置过期时间 30秒后过期
	client.Expire(key, time.Second*300)
	client.ExpireAt(key, time.Now().Add(time.Second*300))
	if err != nil {
		log := UitlLog()
		log.Error("redis err" + err.Error())
		return err
	}
	return err
}

func GetRedis(msg_id string) ([]string, error) {
	client := rconnect()
	defer client.Close()
	key := "msg" + msg_id
	val, err := client.ZRange(key, 0, -1).Result()
	if err != nil {
		log := UitlLog()
		log.Error("redis err" + err.Error())
		return nil, err
	}
	return val, nil
}
